package com.zhuifeng.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhuifeng.search.client.GulimallElasticSearchConfig;
import com.zhuifeng.search.domain.Product;
import com.zhuifeng.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SearchServiceImpl implements ISearchService {

    private final RestHighLevelClient client;

    private final static String INDEX_NAME = "product_info";

    public SearchServiceImpl() {
        GulimallElasticSearchConfig gulimallElasticSearchConfig = new GulimallElasticSearchConfig();
        this.client = gulimallElasticSearchConfig.esRestClient();
    }

    @Override
    public void productPutaway(Product product) {
        try {
            IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
            indexRequest.id(product.getProductId());
            indexRequest.source(JSONObject.toJSONString(product), XContentType.JSON);
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void productSold(String productId) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME);
            deleteRequest.id(productId);
            client.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
